##########################################
# 将混合在一起的 WORD文件 和 PDF文件 分类归档  #
##########################################
import os
import shutil
from queue import Queue


# 建立新的文件夹
def make_new_dir(source_dir, file_type):
    for ft in file_type:
        new_ft = os.path.join(source_dir, ft)
        # print(new_ft)
        if not os.path.isdir(new_ft):
            os.makedirs(new_ft)


# 遍历目录并存入队列
def write_to_q(path_to_write, q: Queue):
    for full_path, dirs, files in os.walk(path_to_write):
        # 如果目录下没有文件。就跳过该目录
        if not files:
            continue
        else:
            q.put(f"{full_path}::{files}")


# 将队列的文件名分类并写入新的文件夹
def classify_from_q(q: Queue, type_to_classify):
    while not q.empty():
        item = q.get()
        # 将路径和文件分开
        filepath, files = item.split("::")
        files = files.strip("[]").split(",")
        # 对每个文件进行处理
        for filename in files:
            # 将文件移动到新的目录
            move_to_newdir(filename, filepath, type_to_classify)


# 移动文件到新的目录
def move_to_newdir(filename_with_ext, file_in_path, type_to_new_path):
    # 获取文件扩展名
    filename_with_ext = filename_with_ext.strip(" \'")
    ext = filename_with_ext.split(".")[1]
    for new_path in type_to_new_path:
        if ext in type_to_new_path[new_path]:
            old_file = os.path.join(file_in_path, filename_with_ext)
            new_file = os.path.join(source_dir, new_path, filename_with_ext)
            print(old_file)
            print(new_file)
            shutil.move(old_file, new_file)


if __name__ == '__main__':
    # 定义要对哪个目录进行文件扩展名分类
    source_dir = './result'
    # 定义文件类型和扩展名
    file_type = {
        "docx": "docx",
        "pdf": "pdf"
    }

    # 建立新的文件夹
    make_new_dir(source_dir, file_type)

    # 定义一个队列
    filename_q = Queue()

    # 遍历目录并存入队列
    write_to_q(source_dir, filename_q)

    # 将队列的文件名分类并写入新的文件夹
    classify_from_q(filename_q, file_type)

    print('生成完毕')
